
import { listFavouredPolicy } from "@/api/payfee/favouredPolicy";
import { getRoom  } from "@/api/property/room";
import { checkRole } from "@/utils/permission";



export const favouredMixin = {
  data(){
    return {
      //优惠政策字典
      listFavouredPolicyOptions:[],
      //优惠折扣是否可编辑
      showDiscount:true,
      //最小折扣率
      minDepositRate:null,
      //减免金额
      reliefAmount:0,
      //当前选中的优惠政策
      selectFavoured:null,
      showFavourableMoney:false
    }
  },
  watch:{
    'form.discount'(v){
      this.discountChange(v)
    }
  },
  created() {


  },
  methods: {
    initFavoured(){
      if(this.pageParam.roomIdArray.length > 0){
        getRoom(this.pageParam.roomIdArray[0]).then(res=>{
          this.getListFavouredPolicy(res.data.communityId)
        })
      }
    },
    getListFavouredPolicy(communityId){
      listFavouredPolicy({communityId:communityId || -1,findTime:this.parseTime(new Date()),status:'102'}).then(res=>{
        this.listFavouredPolicyOptions = res.rows
    })
    },
    //检查收费政策   应用于那些收费项目
    checkNormId(v) {
      if(this.selectFavoured && this.selectFavoured.preferentialMethod){
        let index = this.selectFavoured.favouredNorms.findIndex(x => x.normId == v)
        if(index != -1){;
          return true
        }
      }
      return false;
    },
    //优惠任免,检查项目是否选中
    checkSelectionRow(row) {
      let index = this.multipleSelection.findIndex(x=>x.id == row.id)
      if(index != -1){
        return true;
      }
      return false;
    },
    //选择优惠政策
    preferentialChange(v){
      this.showFavourableMoney = false
      if(this.multipleSelection.length < 1){
        this.msgError("请选择收费项目!")
        this.form.preferentialId = null;
        return;
      }
      let index = this.listFavouredPolicyOptions.findIndex(x=>x.favouredPolicyId == v);
      if(index != -1){
          let row = this.listFavouredPolicyOptions[index]
          this.selectFavoured = row;
          //折扣
          if(row.preferentialMethod == this.feeConstants.preferential_method.zk){
              this.computeZk(row);
          }else if(row.preferentialMethod == this.feeConstants.preferential_method.rm){
            //任免
              this.computeRm(row);
          }else if(row.preferentialMethod == this.feeConstants.preferential_method.jm){
            //减免
            this.computeJm(row);
          }else if(row.preferentialMethod == this.feeConstants.preferential_method.zs){
            //赠送
            this.computeZs(row);
          }else if(row.preferentialMethod == this.feeConstants.preferential_method.djyh){
            //单价优惠
            this.computeDjyh(row);
          }
      }else{
        this.preferentialClear()
      }
    },
    //清除优惠政策
    preferentialClear(){
      this.refreshList();
      this.selectFavoured = null
      this.form.discount = null
      this.showFavourableMoney = false
    },
    refreshList(){
      if(this.selectFavoured){
        this.receivableList.forEach((row) => {
          let index = this.multipleSelection.findIndex(x=>x.id == row.id);
          if(index != -1){
            if( row.ruleCostList &&  row.ruleCostList.length > 0){
              row.ruleCostList.forEach((column) => {
                column.paidMoney = column.amountOwed
                column.specialMoney = 0
                column.preferentialId = null
              })
            }
          }
        })
        this.computeReceivableList();
      }
    },
    //计算折扣
    computeZk(row){
      this.refreshList()
      let favouredConfs = row.favouredConfs;
      let roleKeys = row.favouredConfs.map((item,index)=>{
        return item.postId;
      });
      let FLAG = false;
      //最折扣率数值
      let minDepositRates = []
      for(let i in row.favouredConfs){
        let role = false;
        let favoured = row.favouredConfs[i];
        role = checkRole([favoured.postId],true);
        if(role){
          FLAG = true
        }
        if(role){
          minDepositRates.push(favoured.depositRate)
        }
      }
      if(FLAG){
        if(row.discountMethod == this.feeConstants.discount_method.kdzk){
          //固定折扣
          this.showDiscount = true
          this.form.discount =  Math.min.apply(null,minDepositRates);
        }else if(row.discountMethod == this.feeConstants.discount_method.zdzk){
          //最低折扣
          this.minDepositRate =  Math.min.apply(null,minDepositRates);
          this.form.discount = null
          this.showDiscount = false;
        }
      }else{
        this.form.preferentialId = null;
        this.showDiscount = true
        this.form.discount = null
        this.msgError("当前账号无权限使用此政策!")
      }
    },
    //计算任免
    computeRm(row){
      this.refreshList();
      this.showDiscount = true
      this.form.discount = null
      let favouredConfs = row.favouredConfs;
      let roleKeys = row.favouredConfs.map((item,index)=>{
        return item.postId;
      });
      let FLAG = false;
      let reliefAmounts = []
      for(let i in row.favouredConfs){
        let role = false;
        let favoured = row.favouredConfs[i];
        role = checkRole([favoured.postId],true);
        if(role){
          FLAG = true
        }
        if(role){
          reliefAmounts.push(favoured.money)
        }
      }
      if(FLAG){
        this.showFavourableMoney = true
        this.reliefAmount =  Math.max.apply(null,reliefAmounts);
        this.msgSuccess("请在收费项最后一列填写优惠金额!")
      }else{
        this.form.preferentialId = null;
        this.showFavourableMoney = false
        this.msgWarning("当前账号无权限使用此政策!")
      }
    },
    //计算减免
    computeJm(row){
      this.refreshList()
      this.showDiscount = true
      this.form.discount = null
      //1、检查选择的费用单是否有满足优惠政策的收费项目
      if(!this.checkJmNorm(row)){
        this.form.preferentialId = null;
        this.msgError("当前选中的优惠政策,没有适用于选中的收费项目")
        return
      }
      let FLAG = false
        if(this.selectFavoured.preferentialType == this.feeConstants.preferential_type.mj){
          //满缴
          let  favouredConfs = row.favouredConfs
          favouredConfs.sort(this.$utils.compareKey(row.favouredConfs,'desc'))
          for(let i in favouredConfs){
            let conf = favouredConfs[i]
            let index = this.multipleSelection.findIndex(fee=> Number(fee.monthNum) >= Number(conf.mature) && conf.normCn=== fee.normId)
            if(index != -1){
              FLAG = true
              if(this.selectFavoured.reliefMethod == this.feeConstants.relief_method.jmgdje){
                //减免固定金额
                this.jmgdje(conf.money,conf.normApply)
              }else if(this.selectFavoured.reliefMethod == this.feeConstants.relief_method.jmydfy){
                //减免方式  减免月度费用
                this.jmydje(conf.derateMonth,conf.normApply)
              }
              break
            }
          }
        }else if(this.selectFavoured.preferentialType == this.feeConstants.preferential_type.qjj){
          for(let i in row.favouredConfs){
            let conf = row.favouredConfs[i]
            //查看有没有符合收费项目的费用区间
            let index = this.multipleSelection.findIndex(fee=> this.$utils.toDateString(fee.beginTime,'yyyy-MM') <= conf.beginMonth && this.$utils.toDateString(fee.finishTime,'yyyy-MM') >= conf.finishMonth)
            if(index != -1){
              FLAG = true
              if(this.selectFavoured.reliefMethod == this.feeConstants.relief_method.jmgdje){
                //减免固定金额
                this.jmgdje(conf.money,conf.normApply)
              }else if(this.selectFavoured.reliefMethod == this.feeConstants.relief_method.jmydfy){
                //减免方式  减免月度费用
                this.jmydje(conf.derateMonth,conf.normApply)
              }
              break
            }
          }
        }
      if(!FLAG){
        this.form.preferentialId = null;
        this.msgError("当前选中的优惠政策,没有适用于选中的收费项目")
        return
      }else{
        this.computeReceivableList();
      }
    },
    //检查选中的收费项目,是否包含在减免政策适用的收费标准
    checkJmNorm(row){
      let FLAG = false
      let normIds = this.multipleSelection.map((item,index)=>{
        return item.normId;
      });
      for(let i in row.favouredConfs){
        let conf = row.favouredConfs[i]
        if(normIds.includes(conf.normCn) && normIds.includes(conf.normApply)){
          FLAG = true
          break
        }
      }
      return FLAG
    },
    //减免固定金额
    jmgdje(jmMoney,normApply){
      for(let i in this.receivableList){
        let row = this.receivableList[i]
        let index = this.multipleSelection.findIndex(x=>x.id == row.id);
        if(index != -1){
          //选中的收费标准==政策应用标准
          if(this.multipleSelection[index].normId === normApply){
            if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.ayjt){
              //金额 / 月数
              let monthMoney = this.$utils.floor( this.$utils.divide(jmMoney,row.monthNum) , 2)
              let totalMoney = 0;
              //按月均摊
              row.ruleCostList.forEach((column, index) => {
                //最后一条
                if(index == row.ruleCostList.length -1){
                  //总金额减去最后一条之前的金额=最后一条数据的优惠金额
                  column.specialMoney = this.$utils.subtract(jmMoney,totalMoney)
                }else{
                  column.specialMoney = monthMoney
                  totalMoney = this.$utils.add(totalMoney,monthMoney)
                }
                //应收金额-优惠金额
                column.paidMoney = this.$utils.subtract(column.amountOwed,column.specialMoney)
                //优惠政策ID
                column.preferentialId = this.selectFavoured.favouredPolicyId
              })
            }else if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.cqwh){
              //当前费用项优惠金额
              let  ruleCostList = this.$utils.orderBy(row.ruleCostList,[['beginTime', 'asc']])
              ruleCostList.forEach((column, index) => {
                if(jmMoney > 0){
                  //优惠金额大于收款金额
                  if(jmMoney > column.receivableMoney){
                    //优惠金额
                    column.specialMoney = column.receivableMoney
                    jmMoney = this.$utils.subtract(jmMoney,column.receivableMoney)
                  }else{
                    //优惠金额不足以 支付当前费用全部费用
                    column.specialMoney = jmMoney
                    jmMoney = 0
                  }
                }
                //应收金额-优惠金额
                column.paidMoney = this.$utils.subtract(column.amountOwed,column.specialMoney)
                //优惠政策ID
                column.preferentialId = this.selectFavoured.favouredPolicyId
              })
              row.ruleCostList = this.$utils.orderBy(ruleCostList,[['beginTime', 'asc']])
            }else if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.chwq){
              //从后往前
              //当前费用项优惠金额
              let  ruleCostList = this.$utils.orderBy(row.ruleCostList,[['beginTime', 'desc']])
              ruleCostList.forEach((column, index) => {
                if (jmMoney > 0) {
                  //优惠金额大于收款金额
                  if (jmMoney > column.receivableMoney) {
                    //优惠金额
                    column.specialMoney = column.receivableMoney
                    jmMoney = this.$utils.subtract(jmMoney, column.receivableMoney)
                  } else {
                    //优惠金额不足以 支付当前费用全部费用
                    column.specialMoney = jmMoney
                    jmMoney = 0
                  }
                }
                //应收金额-优惠金额
                column.paidMoney = this.$utils.subtract(column.amountOwed, column.specialMoney)
                //优惠政策ID
                column.preferentialId = this.selectFavoured.favouredPolicyId
              })
              row.ruleCostList = this.$utils.orderBy(ruleCostList,[['beginTime', 'asc']])
            }
          }

        }


      }
    },
    //减免月度费用
    jmydje(derateMonth,normApply){
      for(let i in this.receivableList){
        let row = this.receivableList[i]
        let index = this.multipleSelection.findIndex(x=>x.id == row.id);
        if(index != -1){
          //选中的收费标准==政策应用标准
          if(this.multipleSelection[index].normId === normApply){
            if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.cqwh){
              //当前费用项优惠金额
              let  ruleCostList = this.$utils.orderBy(row.ruleCostList,[['beginTime', 'asc']])
              ruleCostList.forEach((column, index) => {
                if(derateMonth > 0){
                  column.specialMoney = column.receivableMoney
                  //应收金额
                  column.paidMoney = 0
                  column.preferentialId = this.selectFavoured.favouredPolicyId
                  derateMonth--
                }
              })
              row.ruleCostList = this.$utils.orderBy(ruleCostList,[['beginTime', 'asc']])
            }else if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.chwq){
              //从后往前
              //当前费用项优惠金额
              let  ruleCostList = this.$utils.orderBy(row.ruleCostList,[['beginTime', 'desc']])
              ruleCostList.forEach((column, index) => {
                if(derateMonth > 0){
                  column.specialMoney = column.receivableMoney
                  //应收金额
                  column.paidMoney = 0
                  column.preferentialId = this.selectFavoured.favouredPolicyId
                  derateMonth--
                }
              })
              row.ruleCostList = this.$utils.orderBy(ruleCostList,[['beginTime', 'asc']])
            }
          }
        }
      }
    },
    //计算赠送
    computeZs(){

    },
    //计算单价优惠
    computeDjyh(){

    },
    //优惠折扣数据变化
    discountChange(v){
      if(!v){
        return;
      }
      //最低固定折扣
      if(this.selectFavoured.discountMethod == this.feeConstants.discount_method.zdzk){
        //当前输入折扣大于最低折扣权限
        if(parseInt(v) < parseInt(this.minDepositRate)){
          this.msgError(`当前账号最低折扣限制是${this.minDepositRate}折`)
          this.form.discount = this.minDepositRate
          return;
        }

        //当前输入折扣大于最低折扣权限
        if(parseInt(v) > 10){
          this.msgError("请输入10以下的整数")
          this.form.discount = this.minDepositRate
          return;
        }

      }
      if(this.multipleSelection && this.multipleSelection.length > 0){
        for(let i in this.receivableList){
          let row = this.receivableList[i]
          let FLAG =  this.checkNormId(row.normId)
          if(!FLAG){
            continue;
          }
          let index = this.multipleSelection.findIndex(x=>x.id == row.id);
          if(index != -1){
            if(row.ruleCostList && row.ruleCostList.length > 0){
              if( row.ruleCostList &&  row.ruleCostList.length > 0){
                row.ruleCostList.forEach((column, index2) => {
                  //优惠政策ID
                  column.preferentialId = this.selectFavoured.favouredPolicyId
                  //实收金额 = 应收金额*（折扣率/10）
                  column.paidMoney = this.$utils.toFixed(this.$utils.multiply(column.amountOwed,this.$utils.divide(v,10)),2)
                  //优惠金额 = 应收金额-优惠金额
                  column.specialMoney =  this.$utils.subtract(column.amountOwed,column.paidMoney)
                })
              }
            }
          }
        }
        this.computeReceivableList();
      }
    },
    //优惠政策任免数据变化
    specialMoneyChange(v,row){
      if(v<1)return;
      let values = this.receivableList.map(item=>{
        return Number(item.specialMoney)
      })
      let sumValue
      if (!values.every(value => isNaN(value))) {
        sumValue = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      }
      if(sumValue > this.reliefAmount){
        this.msgError(`当前操作人员,最大任免权限是[${this.reliefAmount}]元`)
        this.receivableList.forEach((rb) => {
          rb.specialMoney = 0
          if(rb.ruleCostList && rb.ruleCostList.length > 0){
            rb.ruleCostList.forEach((rule, index) => {
              rule.specialMoney = 0
              rule.paidMoney = rule.amountOwed
              rule.preferentialId = null
            })
          }
        })
      }else{
        if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.ayjt){
          //金额 / 月数
          let monthMoney = this.$utils.floor( this.$utils.divide(v,row.monthNum) , 2)
          let totalMoney = 0;
          //按月均摊
          row.ruleCostList.forEach((column, index) => {
            //最后一条
            if(index == row.ruleCostList.length -1){
              //总金额减去最后一条之前的金额=最后一条数据的优惠金额
              column.specialMoney = this.$utils.subtract(v,totalMoney)
            }else{
              column.specialMoney = monthMoney
              totalMoney = this.$utils.add(totalMoney,monthMoney)
            }
            //应收金额-优惠金额
            column.paidMoney = this.$utils.subtract(column.amountOwed,column.specialMoney)
            //优惠政策ID
            column.preferentialId = this.selectFavoured.favouredPolicyId
          })
        }else if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.cqwh){
          //当前费用项优惠金额
          let rowSpecialMoney = v
          let  ruleCostList = this.$utils.orderBy(row.ruleCostList,[['beginTime', 'asc']])
          ruleCostList.forEach((column, index) => {
            if(rowSpecialMoney > 0){
              //优惠金额大于收款金额
              if(rowSpecialMoney > column.receivableMoney){
                //优惠金额
                column.specialMoney = column.receivableMoney
                rowSpecialMoney = this.$utils.subtract(rowSpecialMoney,column.receivableMoney)
              }else{
                //优惠金额不足以 支付当前费用全部费用
                column.specialMoney = rowSpecialMoney
                rowSpecialMoney = 0
              }
            }
            //应收金额-优惠金额
            column.paidMoney = this.$utils.subtract(column.amountOwed,column.specialMoney)
            //欠费金额
            // column.amountOwed = this.$utils.subtract(column.amountOwed,column.specialMoney)
            //优惠政策ID
            column.preferentialId = this.selectFavoured.favouredPolicyId
          })
          row.ruleCostList = this.$utils.orderBy(ruleCostList,[['beginTime', 'asc']])
        }else if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.chwq){
          //从后往前
          //当前费用项优惠金额
          let rowSpecialMoney = v
          let  ruleCostList = this.$utils.orderBy(row.ruleCostList,[['beginTime', 'desc']])
          ruleCostList.forEach((column, index) => {
            if (rowSpecialMoney > 0) {
              //优惠金额大于收款金额
              if (rowSpecialMoney > column.receivableMoney) {
                //优惠金额
                column.specialMoney = column.receivableMoney
                rowSpecialMoney = this.$utils.subtract(rowSpecialMoney, column.receivableMoney)
              } else {
                //优惠金额不足以 支付当前费用全部费用
                column.specialMoney = rowSpecialMoney
                rowSpecialMoney = 0
              }
            }
            //应收金额-优惠金额
            column.paidMoney = this.$utils.subtract(column.amountOwed, column.specialMoney)
            //欠费金额
            // column.amountOwed = this.$utils.subtract(column.amountOwed, column.specialMoney)
            //优惠政策ID
            column.preferentialId = this.selectFavoured.favouredPolicyId
          })
          row.ruleCostList = this.$utils.orderBy(ruleCostList,[['beginTime', 'asc']])
        }else if(this.selectFavoured.sharingMethod == this.feeConstants.sharing_method.ajejt){
          //按金额均摊

        }
      }
      this.computeReceivableList();
      console.log("--------------"+sumValue+"-----------------------")

    }
  }


}
